<?php
/**
 * 优惠券服务
 * @author flaravel
 */
namespace App\Service;

use App\Models\Coupon;
use App\Models\MemberCoupon;
use Illuminate\Support\Facades\Auth;

class CouponService
{
    private $coupon;

    public function __construct()
    {
        $this->coupon = new Coupon();
    }

    /**
     * 获取 绑定手机号送的优惠券
     * @return mixed
     */
    public function getBindMobileCoupon()
    {
        $couponId = app(ConfigService::class)->getBindMobileCoupons();
        return $this->coupon->whereIn('id', explode(',', $couponId))->get();
    }

    /**
     * 分享领取优惠券
     * @param Coupon $coupon
     * @param $user_id
     * @return bool
     */
    public function giveShareCouponToUser(Coupon $coupon, $user_id)
    {
        $time = $this->computedExporedTime($coupon);
        //领取前判断是否已经领取过（未使用的）
        if(MemberCoupon::where('user_id', $user_id)
            ->where('coupon_id', $coupon->id)
            ->where('use_at', null)
            ->where('end_time', '>', now())->count() >= 5
        ) {
            return false;
        }
        return MemberCoupon::create([
            'coupon_id' => $coupon->id,
            'user_id' => $user_id,
            'start_time' => $time['start_time'],
            'end_time' => $time['end_time']
        ]);
    }
    /**
     * 发送优惠券给用户
     *
     * @param Coupon $coupon
     * @param $user_id
     * @return mixed
     */
    public function giveCouponToUser(Coupon $coupon, $user_id)
    {
        $time = $this->computedExporedTime($coupon);
        //领取前判断是否已经领取过（未使用的）
        if(MemberCoupon::where('user_id', $user_id)
            ->where('coupon_id', $coupon->id)
            ->where('use_at', null)
            ->where('end_time', '>', now())->exists()
        ) {
            return false;
        }
        return MemberCoupon::create([
            'coupon_id' => $coupon->id,
            'user_id' => $user_id,
            'start_time' => $time['start_time'],
            'end_time' => $time['end_time']
        ]);
    }

    /**
     * 获取优惠券的有效时间
     *
     * @param Coupon $coupon
     * @return array
     */
    public function computedExporedTime(Coupon $coupon)
    {
        //领取后生效 根据天数直接返回对应的过期时间
        if($coupon->time_out_type == 1)
        {
            $data['start_time'] = now();

            $data['end_time'] = now()->addDays($coupon->date);
        } else {
            $data['start_time'] = $coupon->start_time;

            $data['end_time'] = $coupon->end_time;
        }

        return $data;
    }

    /**
     * h5领券页面
     * 最多十张
     */
    public function getCouponList()
    {
        return $this->coupon->where('is_receive', 1)->take(10)->get();
    }
}
